package com.cn.shuangzi.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Outline;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Process;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.SZBaseWebActivity;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.bean.MaterialsInfo;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.view.AlertWidget;
import com.cn.shuangzi.view.ColorClickableSpan;
import com.google.gson.Gson;
import com.umeng.message.PushAgent;

import org.apaches.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;
import cc.shinichi.library.ImagePreview;
import cc.shinichi.library.view.listener.OnBigImagePageChangeListener;
import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by CN.
 */

public class SZUtil {
    public static void log(String msg) {
        if (SZManager.getInstance().isDebugMode()) {
            Log.v("CN", "=======================");
            Log.v("CN", msg);
            Log.v("CN", "=======================");
        }
    }

    public static void logError(String msg) {
        if (SZManager.getInstance().isDebugMode()) {
            Log.e("CN", "=======================");
            Log.e("CN", msg);
            Log.e("CN", "=======================");
        }
    }

    public static String getPayTypeName(String payType){
        switch (payType){
            case SZConst.ALIPAY:
                return "支付宝";
            case SZConst.WXPAY:
                return "微信支付";
        }
        return "";
    }
    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }


    public static String getPhoneChannel() {
        String brand = Build.BRAND;
        String manufacturer = Build.MANUFACTURER;
        String channel = "";
        if(manufacturer == null){
            manufacturer = "";
        }
        if (brand != null) {
            if (lowerCaseContains(brand,"oppo") || lowerCaseContains(brand,"oneplus")
            ||lowerCaseContains(manufacturer,"oppo") || lowerCaseContains(manufacturer,"oneplus")) {
                channel = "oppo";
            } else if (lowerCaseContains(brand,"honor") || lowerCaseContains(manufacturer,"honor")) {
                channel = "honor";
            } else if (lowerCaseContains(brand,"huawei") || lowerCaseContains(manufacturer,"huawei")) {
                channel = "huawei";
            } else if (lowerCaseContains(brand,"honor") || lowerCaseContains(manufacturer,"honor")) {
                channel = "honor";
            } else if (lowerCaseContains(brand,"vivo") || lowerCaseContains(manufacturer,"vivo")) {
                channel = "vivo";
            } else if (lowerCaseContains(brand,"xiaomi") || lowerCaseContains(manufacturer,"xiaomi")) {
                channel = "xiaomi";
            } else if (lowerCaseContains(brand,"samsung") || lowerCaseContains(manufacturer,"samsung")) {
                channel = "samsung";
            }
        }
        return channel;
    }
    private static boolean lowerCaseContains(String parent,String child){
        if(parent!=null) {
            return parent.toLowerCase().contains(child);
        }
        return false;
    }
    public static void openAppPermissionSettings(Context context, String permission) {
        try {
            switch (getPhoneChannel()) {
                case "vivo":
                    openVivoAppPermissionSettings(context);
                    return;
                case "xiaomi":
                    openXiaomiPermissionSettings(context);
                    return;
                case "oppo":
                    openOppoAppPermissionSettings(context, permission);
                    return;
                default:
                    openAppDetailSetting(context);
                    return;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            openAppDetailSetting(context);
        }
    }

    private static String getSystemProperty(String propName) {
        String result = null;
        try {
            Class<?> clz = Class.forName("android.os.SystemProperties");
            Method get = clz.getMethod("get", String.class);
            result = (String) get.invoke(clz, propName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static void openOppoAppPermissionSettings(Context context, String permission) {
        ArrayList<String> arrayList = new ArrayList<>();
        if (SZValidatorUtil.isValidString(permission)) {
            arrayList.add(permission);
        }
        openOppoAppPermissionSettings(context, arrayList);
    }

    private static void openOppoAppPermissionSettings(Context context, ArrayList<String> permissionList) {
        //新增定义常量
        String EXTRA_PERMISSION_LIST = "permissionList";
        String EXTRA_IS_GET_PERMISSION = "isGetPermission";
        //指定应用详情页Action
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //指定应用包名
        intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        //以上为原生逻辑，接入方可用此Action识别接入点，无需额外修改
        //使用ArrayList传入受阻的权限列表
        if (SZValidatorUtil.isValidList(permissionList)) {
            Bundle bundle = new Bundle();
            bundle.putStringArrayList(EXTRA_PERMISSION_LIST, permissionList);
            intent.putExtras(bundle);
        }
        //传入跳转优化标识
        intent.putExtra(EXTRA_IS_GET_PERMISSION, true);
        //#endif 本接口新增逻辑
        //启动目标界面（保持原有写法）
        context.startActivity(intent);
    }

    private static void openVivoAppPermissionSettings(Context context) {
        Intent intent = new Intent();
//        intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.PurviewTabActivity"));
        intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity"));
        intent.putExtra("packagename", context.getPackageName());
        context.startActivity(intent);
    }


    private static void openXiaomiPermissionSettings(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
        intent.putExtra("extra_pkgname", context.getPackageName());
        context.startActivity(intent);
    }

    public static void showAgreeProtocolAlert(final SZBaseActivity activity, String txtBtnAgree, String protocolName,
                                              final String protocolUrl, final Class<? extends SZBaseWebActivity> webActivity,
                                              final View.OnClickListener onClickAgreeListener) {
        final AlertWidget alertWidget = new AlertWidget(activity);
        alertWidget.show(R.layout.alert_agree_protocol);
        alertWidget.setCancelable(false);

        TextView txtAgreeProtocolDesc = alertWidget.getWindow().findViewById(R.id.txtAgreeProtocolDesc);
        String desc = activity.getString(R.string.agree_protocol_content_one, protocolName);
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(desc);
        stringBuilder.setSpan(new ColorClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                activity.startActivity(protocolUrl, webActivity);
            }
        }, desc.indexOf(protocolName), desc.indexOf(protocolName) + protocolName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        txtAgreeProtocolDesc.setText(stringBuilder);
        txtAgreeProtocolDesc.setHighlightColor(activity.getResources().getColor(android.R.color.transparent));
        txtAgreeProtocolDesc.setMovementMethod(LinkMovementMethod.getInstance());
        TextView txtClose = alertWidget.getWindow().findViewById(R.id.txtClose);
        TextView txtAgree = alertWidget.getWindow().findViewById(R.id.txtAgree);
        txtAgree.setText(txtBtnAgree);

        txtClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertWidget.close();
            }
        });
        txtAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertWidget.close();
                if (onClickAgreeListener != null) {
                    onClickAgreeListener.onClick(v);
                }
            }
        });

    }

    public static void showAgreeTwoProtocolAlert(final SZBaseActivity activity, String txtBtnAgree,
                                                 String protocolName1, final String protocolUrl1, String protocolName2,
                                                 final String protocolUrl2, final Class<? extends SZBaseWebActivity> webActivity,
                                                 final View.OnClickListener onClickAgreeListener) {
        final AlertWidget alertWidget = new AlertWidget(activity);
        alertWidget.show(R.layout.alert_agree_protocol);
        alertWidget.setCancelable(false);

        TextView txtAgreeProtocolDesc = alertWidget.getWindow().findViewById(R.id.txtAgreeProtocolDesc);
        String desc = activity.getString(R.string.agree_protocol_content_two, protocolName1, protocolName2);
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(desc);
        stringBuilder.setSpan(new ColorClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                activity.startActivity(protocolUrl1, webActivity);
            }
        }, desc.indexOf(protocolName1), desc.indexOf(protocolName1) + protocolName1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        stringBuilder.setSpan(new ColorClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                activity.startActivity(protocolUrl2, webActivity);
            }
        }, desc.indexOf(protocolName2), desc.indexOf(protocolName2) + protocolName2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        txtAgreeProtocolDesc.setText(stringBuilder);
        txtAgreeProtocolDesc.setHighlightColor(activity.getResources().getColor(android.R.color.transparent));
        txtAgreeProtocolDesc.setMovementMethod(LinkMovementMethod.getInstance());

        TextView txtClose = alertWidget.getWindow().findViewById(R.id.txtClose);
        TextView txtAgree = alertWidget.getWindow().findViewById(R.id.txtAgree);
        txtAgree.setText(txtBtnAgree);

        txtClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertWidget.close();
            }
        });
        txtAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertWidget.close();
                if (onClickAgreeListener != null) {
                    onClickAgreeListener.onClick(v);
                }
            }
        });

    }

    public static boolean isUserInfoSynchronizationSuccess() {
        return new SZXmlUtil(SZConst.USER_INFO_SZ).getBoolean("synchronization", false);
    }

    public static void setSynchronizationUserInfo(boolean isSuccess) {
        new SZXmlUtil(SZConst.USER_INFO_SZ).put("synchronization", isSuccess);
    }

    public static boolean isAppForeground(Context context) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
        //获取app运行中的process集合
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();
        if (runningAppProcessInfoList == null) {
            return false;
        }
        //processInfo.processName是进程名
        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
            //判断进程的重要级别和进程名与包名的比较
            //ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND表示这个进程在前台
            if (processInfo.processName.equals(context.getPackageName())
                    && (processInfo.importance ==
                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                return true;
            }
        }
        return false;
    }

    public static String getFloatShow(float number) {
        try {
            String numberStr = String.valueOf(number);
            if (numberStr != null) {
                if (numberStr.endsWith(".00")) {
                    return numberStr.replace(".00", "");
                } else if (numberStr.endsWith(".0")) {
                    return numberStr.replace(".0", "");
                }
                return numberStr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getDoubleShow(double number) {
        try {
            String numberStr = String.valueOf(number);
            if (numberStr != null) {
                if (numberStr.endsWith(".00")) {
                    return numberStr.replace(".00", "");
                } else if (numberStr.endsWith(".0")) {
                    return numberStr.replace(".0", "");
                }
                return numberStr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean hasPermission(Context context, String permission) {
        return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    public static boolean hasPermissions(Context context, String[] permissions) {
        for (String permission : permissions) {
            if (!hasPermission(context, permission)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isSignToday(String userId) {
        long signTime = new SZXmlUtil(userId).getLong("sign_date");
        if (signTime == 0) {
            return false;
        }
        if (SZDateUtil.isToday(new Date(signTime))) {
            return true;
        }
        return false;
    }

    public static void sign(String userId) {
        new SZXmlUtil(userId).put("sign_date", System.currentTimeMillis());
    }

    /**
     * 保存图片到相册
     */
    public static boolean saveImageToGallery(Context context, Bitmap mBitmap) {
        return saveImageToGallery(context, mBitmap, System.currentTimeMillis() + ".jpg");
    }

    public static boolean saveImageToGallery(Context context, Bitmap mBitmap, String fileName) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            SZToast.error("未检测到可用的SD卡~");
            return false;
        }
        // 首先保存图片
        File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        // 其次把文件插入到系统图库
        try {
            return insertMedia(context, file, true);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        // 最后通知图库更新
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "")));
//        return true;
    }

    public static boolean insertMedia(Context context, File file, boolean isImg) {
        if (file == null || !file.exists()) {
            return false;
        }
        //判断android Q  (10 ) 版本
        if (isAndroidQ()) {
            try {
                if (isImg) {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Video.Media.DATA, file.getAbsolutePath());
                    values.put(MediaStore.Video.Media.DISPLAY_NAME, file.getName());
                    values.put(MediaStore.Video.Media.MIME_TYPE, "video/*");
                    values.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
                    values.put(MediaStore.Video.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
                    ContentResolver resolver = context.getContentResolver();
                    resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {//老方法
            if (isImg) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, String.valueOf(System.currentTimeMillis()));
                context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
            } else {
                ContentResolver localContentResolver = context.getContentResolver();
                ContentValues localContentValues = getVideoContentValues(new File(file.getAbsolutePath()), System.currentTimeMillis());
                Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
            }
            return true;
        }
    }

    public static boolean isAndroidQ() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    }

    public static ContentValues getVideoContentValues(File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put(MediaStore.Video.Media.TITLE, paramFile.getName());
        localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, paramFile.getName());
        localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        localContentValues.put(MediaStore.Video.Media.DATE_TAKEN, Long.valueOf(paramLong));
        localContentValues.put(MediaStore.Video.Media.DATE_MODIFIED, Long.valueOf(paramLong));
        localContentValues.put(MediaStore.Video.Media.DATE_ADDED, Long.valueOf(paramLong));
        localContentValues.put(MediaStore.Video.Media.DATA, paramFile.getAbsolutePath());
        localContentValues.put(MediaStore.Video.Media.SIZE, Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    public static boolean isRequestVip() {
        return new SZXmlUtil(SZConst.SETTING).getBoolean("is_request_vip_info");
    }

    public static void setRequestVip(boolean isRequest) {
        new SZXmlUtil(SZConst.SETTING).put("is_request_vip_info", isRequest);
    }

//    public static boolean isFirstShowInteractionAd() {
//        return new SZXmlUtil(SZConst.SETTING).getBoolean("is_first_show_interaction", true);
//    }
//
//    public static void setShownInteractionAd() {
//        new SZXmlUtil(SZConst.SETTING).put("is_first_show_interaction", false);
//    }
//
//    public static Class<?> getBuyVipClass(Class<?> classBuyVip, boolean isSetInteractionAdShown) {
//        boolean isFirstShow = isFirstShowInteractionAd();
//        Class<?> classResult = isFirstShow ? classBuyVip : null;
//        if (isSetInteractionAdShown && isFirstShow) {
//            setShownInteractionAd();
//        }
//        return classResult;
//    }

    public static String getUUID() {
        try {
            return UUID.randomUUID().toString().replace("-", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isAlertOnPermissionReallyDeclined() {
        SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
        boolean isAlert = szXmlUtil.getBoolean("is_alert_on_permission_die", false);
        if (isAlert) {
            long time = szXmlUtil.getLong("time_permission_die");
            if (time > 0) {
                isAlert = (System.currentTimeMillis() - time) > SZConst.REQUEST_PERMISSION_IN_SPLASH_INTERVAL;
            } else {
                isAlert = false;
            }
        }
        return isAlert;
    }

    public static void setTimeOnRequestPermission() {
        SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
        szXmlUtil.put("is_alert_on_permission_die", true);
        long time = szXmlUtil.getLong("time_permission_die");
        boolean isSet = (System.currentTimeMillis() - time) > SZConst.REQUEST_PERMISSION_IN_SPLASH_INTERVAL;
        if (isSet) {
            szXmlUtil.put("time_permission_die", System.currentTimeMillis());
        }
    }

    public static boolean isUsedByDuration(long duration) {
        SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
        long time = szXmlUtil.getLong("first_use_time");
        if (time == 0) {
            return false;
        }
        return (System.currentTimeMillis() - time) > duration;
    }

    public static boolean isUsedByOneDay() {
        return isUsedByDuration(SZDateUtil.ONE_DAY);
    }

    public static void setRequestPermissionInSplashDone() {
        SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
        szXmlUtil.put("is_request_permission_in_splash", true);
    }

    public static boolean isRequestPermissionInSplashDone() {
        SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
        return szXmlUtil.getBoolean("is_request_permission_in_splash", false);
    }

    public static boolean isShowPermissionWithFirstUse(boolean isFirstUse) {
        SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
        if (isFirstUse) {
            szXmlUtil.put("first_use_time", System.currentTimeMillis());
            return false;
        }
        return (System.currentTimeMillis() - szXmlUtil.getLong("first_use_time")) > SZConst.FIRST_TIME_REQUEST_PERMISSION_INTERVAL;
    }

    public static boolean isNeedRequestMainPermission(boolean isFirstUse) {
        if (isShowPermissionWithFirstUse(isFirstUse)) {
            if (isRequestPermissionInSplashDone()) {
                SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
                long time = szXmlUtil.getLong("time_permission_die");
                if (time > 0) {
                    return (System.currentTimeMillis() - time) > SZConst.REQUEST_PERMISSION_IN_SPLASH_INTERVAL;
                } else {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    public static boolean isAgreePrivacy() {
        return new SZXmlUtil("privacy_alert").getBoolean("is_privacy_alert");
    }

    public static int[] getScreenLocation(View view) {
        int[] location = new int[2];
        view.getLocationInWindow(location);
        int x = location[0];
        int y = location[1];
        return location;
    }

    public static int getXScreenLocation(View view) {
        return getScreenLocation(view)[0];
    }

    public static int getYScreenLocation(View view) {
        return getScreenLocation(view)[1];
    }

    public static int getResId(String resName, String resType) {
        try {
            return SZApp.getInstance().getResources().getIdentifier(resName,//需要转换的资源名称
                    resType,        //资源类型
                    SZApp.getInstance().getPackageName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //    public static void saveUToken(String token) {
//        new SZXmlUtil("um_token").put("um_token", token);
//    }
//
    public static void clearUToken() {
        new SZXmlUtil("um_token").clear();
    }

    public static String getUToken() {
        return PushAgent.getInstance(SZApp.getInstance()).getRegistrationId();
//        return new SZXmlUtil("um_token").getString("um_token");
    }

    public static void setMaterialsBanner(final Context context, View bannerView, List<MaterialsInfo> bannerList,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener) {
        setMaterialsBanner(context, bannerView, bannerList, null, bannerClickListener);
    }

    public static void setMaterialsBanner(final Context context, View bannerView, List<MaterialsInfo> bannerList, final SZImageLoader imageLoader,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener) {
        setMaterialsBanner(context, bannerView, bannerList, imageLoader, bannerClickListener, null,null);
    }
    public static void setMaterialsBanner(final Context context, View bannerView, List<MaterialsInfo> bannerList, final SZImageLoader imageLoader,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener, ViewPager.OnPageChangeListener onPageChangeListener) {
        setMaterialsBanner(context, bannerView, bannerList, imageLoader, bannerClickListener, null,onPageChangeListener);
    }

    public static void setMaterialsBanner(final Context context, final View bannerView, List<MaterialsInfo> bannerList, final SZImageLoader imageLoader,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener, BGABanner.Adapter<RelativeLayout, MaterialsInfo> bannerAdp, ViewPager.OnPageChangeListener onPageChangeListener) {
        BGABanner banner = bannerView.findViewById(R.id.banner);
        ImageView imgBannerClose = bannerView.findViewById(R.id.imgBannerClose);
        imgBannerClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bannerView.setVisibility(View.GONE);
            }
        });
        if (SZValidatorUtil.isValidList(bannerList)) {
            bannerView.setVisibility(View.VISIBLE);
            final SZImageLoader szImageLoader;
            if (imageLoader == null) {
                szImageLoader = new SZImageLoader(context);
            } else {
                szImageLoader = imageLoader;
            }
            if (bannerList.size() == 1) {
                banner.setAllowUserScrollable(false);
                banner.setAutoPlayAble(false);
            } else {
                banner.setAllowUserScrollable(true);
                banner.setAutoPlayAble(true);
            }
            banner.setData(R.layout.item_banner, bannerList, null);
            banner.setDelegate(new BGABanner.Delegate<RelativeLayout, MaterialsInfo>() {
                @Override
                public void onBannerItemClick(BGABanner banner, RelativeLayout itemView, MaterialsInfo model, int position) {
                    if (!model.onClick(context)) {
                        if (bannerClickListener != null) {
                            bannerClickListener.onBannerItemClick(banner, itemView, model, position);
                        }
                    }
                }
            });
            if(onPageChangeListener!=null) {
                banner.setOnPageChangeListener(onPageChangeListener);
            }
            if (bannerAdp == null) {
                banner.setAdapter(new BGABanner.Adapter<RelativeLayout, MaterialsInfo>() {
                    @Override
                    public void fillBannerItem(BGABanner banner, RelativeLayout itemView, MaterialsInfo materialsInfo, int position) {
                        ImageView imgGoods = itemView.findViewById(R.id.imgBanner);
                        szImageLoader.load(imgGoods, materialsInfo.getImage());
                    }
                });
            } else {
                banner.setAdapter(bannerAdp);
            }
        } else {
            bannerView.setVisibility(View.GONE);
        }
    }

    public static void openTBPage(Context context, String url) {
        if (isAppInstalled("com.taobao.taobao")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String urlTB = "tbopen://m.taobao.com/tbopen/index.html?h5Url=" + URLEncoder.encode(url);
            intent.setData(Uri.parse(urlTB));
            context.startActivity(intent);
        } else {
            openSystemWeb(context, url);
        }
    }

    public static void openJDPage(Context context, String url) {
        if (isAppInstalled("com.jingdong.app.mall")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String urlJD = "openapp.jdmobile://virtual?params=" + URLEncoder.encode(
                    "{\"category\":\"jump\",\"des\":\"m\",\"url\":\"" + url + "\"}"
            );
            intent.setData(Uri.parse(urlJD));
            context.startActivity(intent);
        } else {
            openSystemWeb(context, url);
        }
    }

    public static void openSystemWeb(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        context.startActivity(intent);
    }

    public static void clipViewCorner(View view, final int pixel) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            view.setClipToOutline(true);
            view.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), pixel);
                    }
                }
            });
        }
    }

    public static String getPhoneNumbers(String text) {
        String regex = "1[23456789]\\d{9}";//正则表达式
        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    public static boolean canShowAd() {
        return isOldUser() && isUsedByOneDay();
    }

    public static boolean isOldUser() {
        return new SZXmlUtil("isOldUser").getBoolean("isOldUser", false);
    }

    public static void setOldUser() {
        new SZXmlUtil("isOldUser").put("isOldUser", true);
    }

    public static void clearOldUser() {
        new SZXmlUtil("isOldUser").clear();
    }

    public static boolean isUsedApp() {
        return new SZXmlUtil("isUsedApp").getBoolean("isUsedApp", false);
    }

    public static void setUsedApp() {
        new SZXmlUtil("isUsedApp").put("isUsedApp", true);
    }

    public static void clearUsedApp() {
        new SZXmlUtil("isUsedApp").clear();
    }

    public static boolean isFirstLoad(String key) {
        if (key == null) {
            key = SZConst.FIRST_LOAD_1;
        }
        return !SZValidatorUtil.isValidString(new SZXmlUtil(SZManager.getInstance().getContext(), SZConst.SETTING).getString(key));
    }

    public static void setFirstLoaded(String key) {
        if (key == null) {
            key = SZConst.FIRST_LOAD_1;
        }
        new SZXmlUtil(SZManager.getInstance().getContext(), SZConst.SETTING).put(key, SZConst.NO);
    }

    public static void showBigImg(Activity activity, String url) {
        showBigImg(activity, url, null, true, false);
    }

    public static void showBigImg(Activity activity, String url, ImagePreview.LoadStrategy loadStrategy) {
        showBigImg(activity, url, loadStrategy, true, false);
    }

    public static void showBigImg(Activity activity, String url, ImagePreview.LoadStrategy loadStrategy
            , boolean isShowDownloadButton, boolean isShowCloseButton) {
        ImagePreview.getInstance()
                .setContext(activity)
                .setIndex(0)
                .setImage(url)
                .setLoadStrategy(loadStrategy == null ? ImagePreview.LoadStrategy.AlwaysOrigin : loadStrategy)
                .setZoomTransitionDuration(300)
                .setShowErrorToast(false)
                .setEnableClickClose(true)
                .setEnableDragClose(true)
                .setEnableUpDragClose(true)
                .setShowCloseButton(isShowCloseButton)
                .setShowDownButton(isShowDownloadButton)
                .setDownIconResId(R.mipmap.ic_download_dark)
//                .setFolderName(SZFileUtil.getInstance().getDownloadPathName())
                .setShowIndicator(true)
                .setErrorPlaceHolder(R.mipmap.ic_placeholder_light_gray).start();
    }

    public static void showBigImg(Activity activity, int index, List<String> imageList,
                                  OnBigImagePageChangeListener onBigImagePageChangeListener) {
        showBigImg(activity, index, imageList, onBigImagePageChangeListener, null);
    }

    public static void showBigImg(Activity activity, int index, List<String> imageList,
                                  OnBigImagePageChangeListener onBigImagePageChangeListener, ImagePreview.LoadStrategy loadStrategy) {
        showBigImg(activity, index, imageList, onBigImagePageChangeListener, loadStrategy, true, false);
    }

    public static void showBigImg(Activity activity, int index, List<String> imageList, OnBigImagePageChangeListener onBigImagePageChangeListener, ImagePreview.LoadStrategy loadStrategy
            , boolean isShowDownloadButton, boolean isShowCloseButton) {
        ImagePreview.getInstance()
                .setContext(activity)
                .setIndex(index)
                .setImageList(imageList)
                .setLoadStrategy(loadStrategy == null ? ImagePreview.LoadStrategy.AlwaysOrigin : loadStrategy)
//                .setFolderName(SZFileUtil.getInstance().getDownloadPathName())
                .setZoomTransitionDuration(300)
                .setBigImagePageChangeListener(onBigImagePageChangeListener)
                .setShowErrorToast(false)
                .setEnableClickClose(true)
                .setEnableDragClose(true)
                .setEnableUpDragClose(true)
                .setShowCloseButton(isShowCloseButton)
                .setShowDownButton(isShowDownloadButton)
                .setDownIconResId(R.mipmap.ic_download_dark)
                .setShowIndicator(true)
                .setErrorPlaceHolder(R.mipmap.ic_placeholder_light_gray).start();
    }

    public static String getUserCenterAvatarUrl(String objName) {
        if (SZValidatorUtil.isValidString(objName)) {
            return "https://center.cdn.xiangmaikeji.com/" + objName;
        }
        return null;
    }

    public static Map<String, String> getErrorEventMap(String platform, String errorCode, String errorMsg) {
        return getErrorEventMap(platform, null, errorCode, errorMsg);
    }

    public static Map<String, String> getErrorEventMap(String platform, String errorId, String errorCode, String errorMsg) {
        Map<String, String> params = new HashMap<>();
        try {
            JSONObject jsonObject = new JSONObject();
            if (errorId != null) {
                jsonObject.put(SZConst.ERROR_ID, errorId);
            }
            jsonObject.put(SZConst.ERROR_MSG, errorMsg);
            jsonObject.put(SZConst.ERROR_CODE, errorCode);
            params.put(platform, jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    @NonNull
    public static String md5(String content) {
        return DigestUtils.md2Hex(content);
    }

    @NonNull
    public static String sha1(String content) {
        return DigestUtils.sha1Hex(content);
    }

    public static String makeSign(String appId, String appKey, long currentTime) {
        String sha1 = DigestUtils.sha1Hex(appKey + currentTime + appKey);
        String md5 = DigestUtils.md5Hex(sha1 + appId);
        return md5;
    }

    public static void hideSoftInput(Activity activity, View view) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    // 調用系統方法分享文件
    public static void shareFile(Context context, File file) {
        if (null != file && file.exists()) {
            Intent share = new Intent(Intent.ACTION_SEND);
            String type = getMimeType(file.getAbsolutePath());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri shareUri = FileProvider.getUriForFile(SZApp.getInstance(), SZApp.getInstance().getPackageName() +
                                ".fileprovider",
                        file);
                share.setType(type);
                share.putExtra(Intent.EXTRA_STREAM, shareUri);
                share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                share.setDataAndType(Uri.fromFile(file), type);
            }
            context.startActivity(Intent.createChooser(share, context.getString(R.string.txt_share)));
        } else {
            SZToast.error(context.getString(R.string.error_share_empty));
        }
    }

    public static MultipartBody.Part prepareFilePart(String partName, String path) {
        File file = new File(path);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse(getMimeType(path)), file);
        return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
    }

    public static String getMimeType(String filePath) {
        try {
            String ext = MimeTypeMap.getFileExtensionFromUrl(filePath);
            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "*/*";
    }


    public static Bitmap getBitmapFromView(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap screenShotBm = view.getDrawingCache();
        Bitmap bitmapNew = duplicateBitmap(screenShotBm);
        try {
            screenShotBm.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
        view.setDrawingCacheEnabled(false);
        view.destroyDrawingCache();//注意,这里需要释放缓存
        return bitmapNew;
    }

    public static Bitmap duplicateBitmap(Bitmap bmpSrc) {
        if (null == bmpSrc) {
            return null;
        }
        int bmpSrcWidth = bmpSrc.getWidth();
        int bmpSrcHeight = bmpSrc.getHeight();
        Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Bitmap.Config.ARGB_8888);
        if (null != bmpDest) {
            Canvas canvas = new Canvas(bmpDest);
            final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
            canvas.drawBitmap(bmpSrc, rect, rect, null);
        }
        return bmpDest;
    }

    public static boolean saveTmpImg(Bitmap bitmap) {
        try {
            File mFile = SZFileUtil.getInstance().getOneTmpPic();                        //将要保存的图片文件
            FileOutputStream outputStream = new FileOutputStream(mFile);     //构建输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);  //compress到输出outputStream
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static HashMap<String, String> json2HashMap(String json) {
        HashMap<String, String> data = new HashMap<String, String>();
        // 将json字符串转换成jsonObject
        try {
            JSONObject jsonObject = new JSONObject(json);
            Iterator it = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            while (it.hasNext()) {
                String key = String.valueOf(it.next());
                String value = jsonObject.get(key) == null ? "" : jsonObject.getString(key);
                data.put(key, value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return data;
    }

    /**
     * ******************
     * 获取版本号(内部识别号)
     *
     * @return ******************
     */
    public static int getVersionCode() {
        return getVersionCode(SZApp.getInstance().getPackageName());
    }

    public static int getVersionCode(String packageName) {
        try {
            PackageInfo pi = SZManager.getInstance().getContext().getPackageManager()
                    .getPackageInfo(packageName, 0);
            return pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * ******************
     * 获取版本名称
     */
    public static String getVersionName() {
        try {
            PackageInfo pi = SZApp.getInstance().getPackageManager()
                    .getPackageInfo(SZApp.getInstance().getPackageName(), 0);
            return pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 字符串截断
    public static String getLimitString(String source, int length) {
        if (null == source) {
            return "";
        } else if (source.length() > length) {
            return source.substring(0, length).replace('\n', ' ') + "...";
        } else {
            return source.replace('\n', ' ');
        }
    }

    public static <T extends View> T findViewById(View view, int id) {
        if (view != null && id > 0) {
            return (T) view.findViewById(id);
        }
        return null;
    }

    /**
     * 时间格式化
     */
    public static String getHMSTime(long seconds) {
        String formatTime;
        String hs, ms, ss;

        long h, m, s;
        h = seconds / 3600;
        m = (seconds % 3600) / 60;
        s = (seconds % 3600) % 60;
        if (h < 10) {
            hs = "0" + h;
        } else {
            hs = "" + h;
        }

        if (m < 10) {
            ms = "0" + m;
        } else {
            ms = "" + m;
        }

        if (s < 10) {
            ss = "0" + s;
        } else {
            ss = "" + s;
        }
        if (hs.equals("00")) {
            formatTime = ms + ":" + ss;
        } else {
            formatTime = hs + ":" + ms + ":" + ss;
        }
        return formatTime;
    }

    /**
     * 时间格式化
     */
    public static String getFullHMSTime(long seconds) {
        String formatTime;
        String hs, ms, ss;

        long h, m, s;
        h = seconds / 3600;
        m = (seconds % 3600) / 60;
        s = (seconds % 3600) % 60;
        if (h < 10) {
            hs = "0" + h;
        } else {
            hs = "" + h;
        }

        if (m < 10) {
            ms = "0" + m;
        } else {
            ms = "" + m;
        }

        if (s < 10) {
            ss = "0" + s;
        } else {
            ss = "" + s;
        }
        formatTime = hs + ":" + ms + ":" + ss;
        return formatTime;
    }

    /**
     * *******************
     * bitmap转byte数组
     *
     * @param bmp
     * @param needRecycle
     * @return *******************
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 获取裁剪图片Intent
     *
     * @param imgSrcUri  需要裁剪图片的uri
     * @param imgDestUri 裁剪后存储图片的uri
     * @param outputX
     * @param outputY
     */
    public static Intent getCropImageIntent(Uri imgSrcUri, Uri imgDestUri, int outputX, int outputY) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imgSrcUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imgDestUri); // no face detection
        return intent;
    }

    public static Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(SZManager.getInstance().getContext().getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /****************
     *
     * 一键加群
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回false表示呼起失败
     ******************/
    public static boolean joinQQGroup(Activity activity, String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            activity.startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    /**
     * 根据apk文件判断该apk是否已经安装
     *
     * @return
     */
    public static boolean isAppInstalled(String appPackageName) {
        if (appPackageName == null) {
            return false;
        }
        return getAppNameByPackageName(appPackageName) == null ? false : true;
    }

    /**
     * ******************
     * 安装apk
     *
     * @param file ******************
     */
    public static boolean installApk(File file) {
        if (SZApp.getInstance() == null)
            return false;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 由于没有在Activity环境下启动Activity,设置下面的标签
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                SZUtil.log("packageInstall:" + SZApp.getInstance().getPackageName());
                Uri apkUri = FileProvider.getUriForFile(SZApp.getInstance(), SZApp.getInstance().getPackageName() +
                                ".fileprovider",
                        file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android" +
                        ".package-archive");
            }
            if (SZApp.getInstance().getTopActivity() != null) {
                SZApp.getInstance().getTopActivity().startActivity(intent);
            } else {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                SZApp.getInstance().startActivity(intent);
            }
            SZUtil.log("启动安装");
            return true;
        } catch (Exception e) {
            SZUtil.log("installException:" + e.getMessage());
            return false;
        }
    }

    /**
     * 通过包名获取应用程序的名称。
     *
     * @param packageName 包名。
     * @return 返回包名所对应的应用程序的名称。
     */
    public static String getAppNameByPackageName(String packageName) {
        PackageManager pm = SZManager.getInstance().getContext().getPackageManager();
        String name = null;
        try {
            name = pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
        } catch (PackageManager.NameNotFoundException e) {
        }
        return name;
    }

    private static boolean launchHonorMarket(Activity context) {
        try {
            String url = "honormarket://details?id=" + context.getPackageName();
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setPackage("com.hihonor.appmarket");
            context.startActivity(intent);
            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
    private static boolean launchVIVOMarketForComment(Activity context) {
        try {
            String url = "market://details?id=" + context.getPackageName() + "&th_name=need_comment";
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage("com.bbk.appstore");
            context.startActivity(intent);
            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    private static boolean launchHuaWeiMarket(Activity context) {
        try {
            if (SZApp.getInstance().getHuaWeiAppId() != null) {
                Intent intent = new Intent("com.huawei.appmarket.appmarket.intent.action.AppDetail.withid");
                intent.setPackage("com.huawei.appmarket");
                intent.putExtra("appId", "C" + SZApp.getInstance().getHuaWeiAppId());
                context.startActivity(intent);
                return true;
            }
        } catch (Exception exception) {
        }
        return false;
    }

    public static void launchCurrentAppStoreForComment(Activity context) {
        boolean isLaunch;
        String channel = getPhoneChannel();
        switch (channel) {
            case "honor":
                isLaunch = launchHonorMarket(context);
                break;
            case "huawei":
                isLaunch = launchHuaWeiMarket(context);
                break;
            case "vivo":
                isLaunch = launchVIVOMarketForComment(context);
                break;
            default:
                isLaunch = launchOtherMarketForComment(context);
                break;
        }
        if(!isLaunch){
            launchOtherMarketForComment(context);
        }
    }

    private static boolean launchOtherMarketForComment(Activity context) {
        boolean isLaunch = false;
        try {
            String url = "market://details?id=" + context.getPackageName();
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            List<ResolveInfo> otherApps = context.getPackageManager().queryIntentActivities(intent, 0);
            for (ResolveInfo app : otherApps) {
                String marketPackageName = app.activityInfo.applicationInfo.packageName;
                if (marketPackageName.equals("com.heytap.market")
                        || marketPackageName.equals("com.oppo.market")) {
                    url = "oaps://mk/developer/comment?pkg=" + context.getPackageName();
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
//                    if (getVersionCode(app.activityInfo.applicationInfo.packageName) >= 84000) {
                        intent.setPackage(app.activityInfo.applicationInfo.packageName);
//                    }
                    intent.setData(Uri.parse(url));
                    context.startActivityForResult(intent, 100);
                    isLaunch = true;
                    break;
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (!isLaunch) {
            launchAppStoreDetail(context, context.getPackageName());
        }
        return true;
    }

    public static void launchAppStoreDetail(Context context, String appPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getWidth();
    }

    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int dip2px(float dpValue) {
        final float scale = SZManager.getInstance().getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = SZManager.getInstance().getContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

//    public static String getSZ_APPID(Context context) {
//        String appId = getAppMetaDataString(context, SZConst.SZ_APPID);
//        if (appId != null && appId.contains("sz_")) {
//            appId = appId.replace("sz_", "");
//        }
//        return appId;
//    }
//
//    public static String getTT_SPLASH_ID(Context context) {
//        return String.valueOf(getAppMetaDataInt(context, "TT_SPLASH_ID"));
//    }
//
//    public static String getGDT_SPLASH_ID(Context context) {
//        return getAppMetaDataString(context, "GDT_SPLASH_ID").substring(4);
//    }
//
//    public static String getTT_APPID(Context context) {
//        return String.valueOf(getAppMetaDataInt(context, "TT_APPID"));
//    }
//
//    public static String getGDT_APPID(Context context) {
//        return String.valueOf(getAppMetaDataInt(context, "GDT_APPID"));
//    }
    public static String getChannel(Context context) {
        return ChannelUtil.getChannel(context);
//        return getAppMetaDataString(context, "UMENG_CHANNEL");
    }

    public static String getAppMetaDataString(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(name);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int getAppMetaDataInt(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return appInfo.metaData.getInt(name);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static long getAppMetaDataLong(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return appInfo.metaData.getLong(name);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static boolean isValidConnect(Context context) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context
                    .CONNECTIVITY_SERVICE);
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    return networkInfo.isConnected();
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    return networkInfo.isConnected();
                }
            }
            return false;
            //API大于23时使用下面的方式进行网络监听
        } else {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context
                    .CONNECTIVITY_SERVICE);

            //获取所有网络连接的信息
            Network[] networks = connMgr.getAllNetworks();
            //通过循环将网络信息逐个取出来
            boolean isWifiConnected = false;
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                if (networkInfo != null) {
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        isWifiConnected = networkInfo.isConnected();
                        break;
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        isWifiConnected = networkInfo.isConnected();
                        break;
                    }
                }
            }
            return isWifiConnected;
        }
    }

    //获取应用设置界面Intent
    public static Intent getAppSettingIntent() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", SZApp.getInstance().getPackageName(), null);
        intent.setData(uri);
        return intent;
    }

    public static <T extends Object> T copyMode(Object json, Class<T> classT) {
        if (json != null) {
            Gson gson = new Gson();
            return new Gson().fromJson(gson.toJson(json), classT);
        }
        return null;
    }

    public static String getSearchBeginTimeExact(String date) {
        return date + " 00:00:00";
    }

    public static String getSearchEndTimeExact(String date) {
        return date + " 23:59:59";
    }

    /**
     * 启动第三方apk
     * <p>
     * 如果已经启动apk，则直接将apk从后台调到前台运行（类似home键之后再点击apk图标启动），如果未启动apk，则重新启动
     */
    public static boolean launchAPP(Context context, String packageName) {
        if (context == null) {
            return false;
        }
        Intent intent = getAppOpenIntentByPackageName(context, packageName);
        if (intent == null) {
            return false;
        }
        context.startActivity(intent);
        return true;
    }

    public static Intent getAppOpenIntentByPackageName(Context context, String packageName) {
        String mainAct = null;
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        @SuppressLint("WrongConstant") List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }

    public static Bitmap getBitmapWeChatShareThumbnail(Bitmap bitMap) {
        return getBitmapThumbnail(bitMap, 99, 99);
    }

    public static Bitmap getBitmapThumbnail(Bitmap bitMap, int widthNew, int heightNew) {
        if (bitMap == null) {
            return null;
        }
        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 设置想要的大小
        int newWidth = widthNew;
        int newHeight = heightNew;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true);
        return newBitMap;
    }

    public static void startActivityFastFromBack(Context context, Class classTo) {
        Intent intent = new Intent(context, classTo);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(context, 0, intent, 0);
        try {
            pendingIntent.send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    public static boolean isIgnoringBatteryOptimizations(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Activity.POWER_SERVICE);
        boolean hasIgnored = true;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        return hasIgnored;
    }

    public static void openIgnoringBatteryOptimizations(Context context) {
        Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        PackageManager packageManager = context.getPackageManager();
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        if (intent.resolveActivity(packageManager) != null) {
            context.startActivity(intent);
        }
    }

    public static boolean checkNotification(Context context) {
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    public static boolean checkNotificationChannel(Context context, String channelId) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (notificationManager.getNotificationChannel(channelId) == null) {
                return true;
            }
            return notificationManager.getNotificationChannel(channelId).getImportance() != NotificationManager.IMPORTANCE_NONE;
        }
        return true;
    }

    //跳转到通知管理
    public static void openNotificationSetting(Context context, String channelId) {
        try {
            // 根据通知栏开启权限判断结果，判断是否需要提醒用户跳转系统通知管理页面
            Intent intent = new Intent();
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            intent.putExtra("app_package", context.getPackageName());
            if (checkNotificationChannel(context, channelId)) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            } else {
                intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelId);
                //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
                intent.putExtra("app_uid", channelId);
            }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            openAppDetailSetting(context);
        }
    }

    //跳转到通知管理
    public static void openNotificationSetting(Context context) {
        try {
            // 根据通知栏开启权限判断结果，判断是否需要提醒用户跳转系统通知管理页面
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            intent.putExtra("app_package", context.getPackageName());
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            openAppDetailSetting(context);
        }
    }

    public static void openAppDetailSetting(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(intent);
    }

    public static boolean isOpenLocationService(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static void openLocationServiceIntent(Activity context, int requestCode) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivityForResult(intent, requestCode);
    }

    public static boolean isServiceRunning(Context context, Class<? extends Service> service) {
        if (service == null)
            return false;
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(500);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(service.getName())) {
                return true;
            }
        }
        return false;
    }

    public static String getHidePhoneStr(String phone) {
        if (SZValidatorUtil.isValidString(phone)) {
            return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
        }
        return "";
    }

    public static void copyClipboard(Context context, String content) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", content);
        cm.setPrimaryClip(mClipData);
    }

    public static String getClipboard(Context context) {
        try {
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData data = cm.getPrimaryClip();
            ClipData.Item item = data.getItemAt(0);
            String content = item.getText().toString();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void ctrlNavigation(Activity activity, final Handler mHandler) {
        final View decorView = activity.getWindow().getDecorView();
        final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int i) {
                if ((i & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            decorView.setSystemUiVisibility(uiOptions);
                        }
                    }, 1000);
                }
            }
        });
    }

    public static View getEmptyView(Context context, int imgResId, int txtResId) {
        View emptyView = LayoutInflater.from(context).inflate(R.layout.item_empty, null);
        ImageView imgEmpty = emptyView.findViewById(R.id.imgEmpty);
        if (imgResId > 0) {
            imgEmpty.setImageResource(imgResId);
        } else if (imgResId == -1) {
            imgEmpty.setVisibility(View.GONE);
        }
        if (txtResId != 0) {
            TextView txtEmpty = emptyView.findViewById(R.id.txtEmpty);
            txtEmpty.setText(txtResId);
        }
        return emptyView;
    }

    public static View getEmptyView(Context context, int imgResId, String txtEmptyData) {
        View emptyView = LayoutInflater.from(context).inflate(R.layout.item_empty, null);
        ImageView imgEmpty = emptyView.findViewById(R.id.imgEmpty);
        if (imgResId > 0) {
            imgEmpty.setImageResource(imgResId);
        } else if (imgResId == -1) {
            imgEmpty.setVisibility(View.GONE);
        }
        if (txtEmptyData != null) {
            TextView txtEmpty = emptyView.findViewById(R.id.txtEmpty);
            txtEmpty.setText(txtEmptyData);
        }
        return emptyView;
    }

    public static View getEmptyView(Context context, int txtResId) {
        return getEmptyView(context, 0, txtResId);
    }

    public static View getEmptyView(Context context, String txtEmptyData) {
        return getEmptyView(context, 0, txtEmptyData);
    }

    public static boolean isTestPhone(String phone) {
        if (!TextUtils.isEmpty(phone)) {
            String[] strings = {"1300000000",
                    "1301111111",
                    "1302222222",
                    "1303333333",
                    "1304444444",
                    "1305555555",
                    "1306666666",
                    "1307777777",
                    "1308888888",
                    "1309999999"};
            for (String string : strings) {
                if (string.equals(phone)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isValidPhoneWithTestPhone(String phone) {
        return isTestPhone(phone) || SZValidatorUtil.isMobile(phone);
    }

    public static boolean isUrlPath(String path) {
        return path != null && path.contains("http");
    }

    public static boolean isNumericValue(String content) {
        try {
            Double.parseDouble(content);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static Bitmap createBitmapThumbnail(Bitmap bitMap) {
        if (bitMap == null) {
            return null;
        }
        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 设置想要的大小
        int newWidth = 99;
        int newHeight = 99;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true);
        return newBitMap;
    }

    public static int getRequestLength(List list) {
        return getRequestLength(list, SZConst.LIMIT);
    }

    public static int getRequestLength(List list, int length) {
        if (SZValidatorUtil.isValidList(list)) {
            if (list.size() > length) {
                int count = (int) Math.ceil(SZArithUtil.div(list.size(), length));
                int size = count * length;
                if (size < length) {
                    size = length;
                }
                return size;
            }
        }
        return length;
    }

    public static String getCurrentProcessName(Context context) {
        int pid = Process.myPid();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null) {
            List<ActivityManager.RunningAppProcessInfo> runningAppList = am.getRunningAppProcesses();
            if (runningAppList != null) {
                for (ActivityManager.RunningAppProcessInfo processInfo : runningAppList) {
                    if (processInfo.pid == pid) {
                        return processInfo.processName;
                    }
                }
            }
        }
        return null;
    }

    public static boolean hasFileManagePower() {
        if (hasSDCard()) {
            PackageManager pm = SZApp.getInstance().getPackageManager();
            boolean permission;
            if (isUseAndroidR()) {
                permission = Environment.isExternalStorageManager();
                SZUtil.logError("targetSdk以及当前设备Sdk 均高于30api 判断是否有外部文件读写权限：" + permission);
            } else {
                permission = PackageManager.PERMISSION_GRANTED ==
                        pm.checkPermission(Manifest.permission
                                .WRITE_EXTERNAL_STORAGE, SZApp.getInstance().getPackageName());
                SZUtil.logError("targetSdk或者当前设备Sdk 低于30api 判断是否有外部文件读写权限：" + permission);
            }
            return permission;
        }
        return false;
    }

    public static boolean hasSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    public static boolean isAndroidR() {
        return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R;
    }

    public static boolean isUseAndroidR() {
        return SZApp.getInstance().getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.R && isAndroidR();
    }
}
